import pandas as pd
import json

data_location = '/root/backend/app1/staticfiles/data.csv'
error_location = '/root/backend/app1/staticfiles/error.txt'

'''
push data:
{
    "request": "push data",
    "data":
    {
        "AC Vrms": 0.0,
        "AC Irms": 0.0,
        "Apparent Power": 0.0,
        "BAT Voltage": 0.0,
        "BAT Current": 0.0,
        "PV Voltage": 0.0,
        "PV Current": 0.0,
        "PLL error": 0.0
    }
}
'''

def push_back(message:dict):
    # adddata = message['data']
    # adddata.update({'PV Power': adddata['PV Voltage'] * adddata['PV Current']})
    # adddata = {key:[value] for key, value in adddata.items()}
    # adddatadf = pd.DataFrame(adddata)
    # print('added data frame', adddatadf)
    # df = pd.read_csv(data_location)
    # df = pd.concat([df, adddatadf])
    # df.to_csv(data_location)
    # del df
    adddata = message['data']
    adddata.update({'PV Power': adddata['PV Voltage'] * adddata['PV Current']})
    with open('/root/backend/datapad/staticfiles/data.json', 'r') as fileptr:
        jsonfile = json.load(fileptr)
        jsonfile['consume'].pop(0)
        jsonfile['consume'].append(adddata['Apparent Power'])
        jsonfile['generate'].pop(0)
        jsonfile['generate'].append(adddata['PV Power'])
        jsonfile['time'].append(jsonfile['time'][0])
        jsonfile['time'].pop(0)
        downjson = jsonfile
    with open('/root/backend/datapad/staticfiles/data.json', 'w') as fileptr:
        json.dump(downjson, fileptr, indent=4)
        
    

def get_consume_data_24():
    df = pd.read_csv(data_location)
    ret = df['Apparent Power'].tail(24)
    del df
    return ret

def get_generate_data_24():
    df = pd.read_csv(data_location)
    ret = df['PV Power'].tail(24).to_numpy().tolist()
    del df
    return ret

error_dict = {
    0: 'High AC voltage',
    1: 'Low AC voltage',
    2: 'High Battery Voltage',
    3: 'Low Battery Voltage',
    4: 'AC current over limit',
    5: 'Battery current over limit',
    6: 'PV fault',
    7: 'MPPT fault',
    8: 'Inverter overheat',
    9: 'Battery overheat',
    10: 'PLL fault',
    11: 'Battery fault'
    # 13~16 reserved for which solar panel is out
}

def error_manage(error_list:int):
    errstr = ''
    for i in range(12):
        if (error_list >> i) & 1 == 1:
            errstr += (error_dict[i+1] + '\n')
    with open('/root/backend/datapad/staticfiles/data.json', 'r') as fileptr:
        jsondata = json.load(fileptr)
    jsondata.update({'error': errstr})
    with open('/root/backend/datapad/staticfiles/data.json', 'w') as fileptr:
        json.dump(jsondata, fileptr, indent=4)

